import twec
import scipy
import numpy as np
import gensim
from gensim.models import Word2Vec
import pandas as pd
import os

#Load models
slice_Democrat = Word2Vec.load("for_twec_compass_Democrat.model")
slice_Republican = Word2Vec.load("for_twec_compass_Republican.model")


def vector_normalize(vector):
    norm = np.linalg.norm(vector)
    result = vector/norm
    return(result)

def distance_for_pol_hate_repub(ner):
    result = (1-scipy.spatial.distance.cosine(vector_normalize(slice_Republican[ner]),vector_normalize(slice_Republican['hate']+slice_Republican["political"])))
    return(result)

def distance_for_pol_hate_demo(ner):
    result = (1-scipy.spatial.distance.cosine(vector_normalize(slice_Democrat[ner]),vector_normalize(slice_Democrat['hate']+slice_Democrat["political"])))
    return(result)


def repub_demo_plot(file = "word_vectors_repub_demo.png"):   
 
    r_script = """
    
        library(tidyverse)        
        library(ggrepel)
        
        top_70_graph = read_csv("top_70_id.csv")   

        pos <- position_jitter(height = 0.1, seed = 2)

        plot_ideo = top_70_graph %>%
          mutate(`Party ID` = ifelse(repub_score>demo_score, "Republican","Democrat")) %>%
          ggplot(aes(x = repub_score, y = demo_score, label = word, color = `Party ID`, shape = `Party ID`)) +
          geom_jitter(position = pos, size = 3) +
          geom_text_repel(max.overlaps = 50,position = pos) +
          scale_colour_viridis_d(option = "magma", end = 0.8) +
          theme_classic() +
          xlab("Distance from the 'Political Hate' vector for Republicans") +
          ylab("Distance from the 'Political Hate' vector for Democrats") +
          theme(legend.position = "bottom") +
          theme(text = element_text(size=15)) 

        ggsave("{}", plot_ideo, width = 10, height = 10)

    """.format(file) 

    with open("temp.R", "w") as f:
        f.write(r_script)
    f.close()

    os.system("Rscript temp.R")

